<?php

namespace Lib;

class Cache implements \Lib\Interfaces\ICache {

    private $path;

    public function __construct($path = '') {
        $this->path = $path;
    }

    public function save($value, $valueID) {
        $str_val = serialize($value);
        $file_name = $this->pathCache($valueID) .
                $this->nameCache($valueID);
        $f = fopen($file_name, 'w+');
        if (flock($f, LOCK_EX)) {
            fwrite($f, $str_val);
            flock($f, LOCK_UN);
        }
        fclose($f);
        unset($str_val);
    }

    public function load($valueID, $time) {
        $file_name = $this->getPathCache($valueID) .
                $this->nameCache($valueID);
        if (!file_exists($file_name))
            return false;
        if ((filemtime($file_name) + $time) < time()) {
            return false;
        }
        if (!$data = file($file_name))
            return false;
        return unserialize(implode('', $data));
    }

    public function delete($valueID) {
        $file_name = $this->getPathCache($valueID) .
                     $this->nameCache($valueID);
        if(is_file($file_name))
            unlink($file_name);
    }

    private function pathCache($valueID) {
        $md5 = $this->nameCache($valueID);
        $first_literal = array($md5{0}, $md5{1}, $md5{2}, $md5{3});
        $path = $this->path . DIRSEP;
        foreach ($first_literal as $dir) {
            $path .= $dir . DIRSEP;
            if (!file_exists(SITE_PATH . $path)) {
                if (!mkdir(SITE_PATH . $path, 0777))
                    return false;
            }
        }
        return SITE_PATH . $path;
    }

    private function getPathCache($valueID) {
        $md5 = $this->nameCache($valueID);
        $first_literal = array($md5{0}, $md5{1}, $md5{2}, $md5{3});
        return SITE_PATH . $this->path . DIRSEP .
                implode(DIRSEP, $first_literal) . DIRSEP;
    }

    private function nameCache($valueID) {
        return md5($valueID);
    }

}

?>
